import {createRouter, createWebHashHistory} from 'vue-router';
import {ElNotification} from 'element-plus';
import config from '@/config';
import {useGlobalStoreHook} from '@/store/global';
import {useDictStoreHook} from "@/store/dict";
import bus from '@/plugins/bus';
import token from '@/utils/token';
import socketUtil from "@/utils/socket";
import modal from "@/utils/modal";
import tool from "@/utils/tool";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {afterEach, beforeEach} from './scrollBehavior';

const globalStore = useGlobalStoreHook();

// 系统静态路由
const staticRoutes = [
    {
        name: 'layout',
        path: '/',
        component: () => import('@/layout/index.vue'),
        redirect: config.DASHBOARD_URL || '/dashboard',
    },
    {
        path: '/login',
        component: () => import('@/layout/login/index.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/user_register',
        component: () => import('@/layout/login/components/userRegister.vue'),
        meta: {
            title: '注册'
        }
    },
    {
        path: '/reset_password',
        component: () => import('@/layout/login/components/resetPassword.vue'),
        meta: {
            title: '重置密码'
        }
    }
];

const route_404 = {
    path: '/:pathMatch(.*)*',
    hidden: true,
    component: () => import('../layout/error/404/index.vue'),
}

let routes_404_r = () => {
}

const router = createRouter({
    history: createWebHashHistory(),
    routes: staticRoutes,
});

// 设置标题
document.title = globalStore.getAppName;

// 判断是否已加载过动态/静态路由
let isGetRouter = false;
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    // 动态标题
    document.title = to.meta.title ? `${to.meta.title} - ${globalStore.getAppName}` : `${globalStore.getAppName}`;

    let userToken = token.getUserToken();

    if (to.path === '/login') {
        if (userToken) {
            next({path: '/'});
            return false;
        } else {
            // 删除路由 (替换当前layout路由)
            router.addRoute(staticRoutes[0]);
            // 删除路由(404)
            routes_404_r()
            isGetRouter = false;
            next();
            return false;
        }
    }

    if (staticRoutes.findIndex((r) => r.path === to.path) >= 0) {
        next();
        return false;
    }

    if (!userToken) {
        next({path: '/login'});
        return false;
    }

    if (to.meta?.category === 'LINK' && to.meta?.url) {
        // 处理超链接
        tool.openLink(to.meta?.url);
        // 返回原来的路由地址
        next({path: from.path});
        return false;
    }

    // 整页路由处理
    if (to.meta.fullpage) {
        to.matched = [to.matched[to.matched.length - 1]];
    }

    // 加载动态/静态路由
    if (!isGetRouter) {
        // 如果当前已经登录做一下初始化操作
        if (userToken) {
            // 初始化字典列表
            useDictStoreHook().initDictTypeList();

            // 初始化 WEB_SOCKET
            socketUtil.initSocket(socketResult => {
                console.log("初始化完成 WEB_SOCKET")
                // 处理本页面的消息，提示，弹窗
                if (socketResult && socketResult.page && socketResult.page === "APP" && socketResult.type === "MODAL") {
                    modal.handleSocketResult("APP", socketResult);
                }
                // 总线，分发给其他页面
                if (socketResult && socketResult.page) {
                    bus.emit(socketResult.page, socketResult)
                }
            }, {});
        }
        // 加载动态路由
        await token.loadDynamicsMenu();
        let menuList = tool.flatAsyncRoutes(tool.filterAsyncRouter(globalStore.getMenuList));
        menuList.forEach((menu) => router.addRoute('layout', menu));
        routes_404_r = router.addRoute(route_404);
        if (to.matched.length === 0) {
            router.push(to.fullPath);
        }
        isGetRouter = true;
    }
    beforeEach(to, from);
    next();
})

router.afterEach((to, from) => {
    afterEach(to, from);
    NProgress.done();
})

router.onError((error) => {
    NProgress.done();
    ElNotification.error({
        title: '路由错误',
        message: error.message,
    });
})

export default router;
